
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/log_util.dart';
import 'package:safetymonitor/app/data/entities/auth/app_upgrade_entity.dart';
import 'package:safetymonitor/global.dart';
import 'package:safetymonitor/modules/home/user/version_info/update_dialog.dart';

/// 版本升级工具
class UpdateUtil {

  /// 下载链接
  static String downloadAddress = '';

  /// 获取版本信息
  static Future<AppUpgradeEntity> getUpgradeInfo() async {
    final res = await HttpUtil().generateGetRequest<AppUpgradeEntity>(Interface.getUpgradeInfoNew).execute();
    AppUpgradeEntity appUpgradeEntity = AppUpgradeEntity();
    res.onSuccess((result) {
      if (result.data != null) {
        appUpgradeEntity = result.data!;
        /// 地址是内网的,手动替换成外网地址
        String apkAddress = appUpgradeEntity?.apkAddress ?? '';
        if(apkAddress == '') {
          AppToast.showError('下载地址为空');
        }
        if(apkAddress.startsWith('http://172.13.200.20:9090')) {
          apkAddress = apkAddress.replaceFirst('http://172.13.200.20:9090', 'http://219.145.189.219:9090');
        }
        downloadAddress = apkAddress ;
      }
    });
    return appUpgradeEntity;
  }

  /// 点击升级
  static void upgrade(AppUpgradeEntity? appUpgradeEntity) {
    Get.dialog(
      barrierDismissible: false,
      PopScope(
        canPop: appUpgradeEntity!.isForceUpgrade == 0,
        onPopInvoked: (bool didPop) {
          if (!didPop) {
            AppToast.showWarning('${'请下载最新版本'}!');
          }
        },
        child: UpdateDialog(
          downloadAddress: downloadAddress,
          isForce: appUpgradeEntity.isForceUpgrade == 1,
          upDateContent: appUpgradeEntity.upgradeDescription,
          version: appUpgradeEntity.appVersion,
        ),
      ),
    );
  }

  /// 更新检查
  static void checkUpdate() async {
    final appUpgradeEntity = await UpdateUtil.getUpgradeInfo();
    // 没有数据
    if (appUpgradeEntity.appVersion.isEmpty) {
      return;
    }
    bool hasNewVersion = false;
    try {
      hasNewVersion = Version.parse(appUpgradeEntity.appVersion) > Version.parse(Global.packageInfo.version);
    } catch (e) {
      AppLogger.log('获取版本信息失败: $e');
    }
    // 如果有新版本弹出弹窗
    if (hasNewVersion) {
      UpdateUtil.upgrade(appUpgradeEntity);
    }
  }
}
